# include "jam.h"
# include "pathsys.h"

void path_parse( const char *file, PATHNAME *f ) {
  const char *p, *q;
  const char *end;
  memset( ( char * )f, 0, sizeof( *f ) );
  if( file[0] == '<' && ( p = strchr( file, '>' ) ) ) {
    f->f_grist.ptr = file;
    f->f_grist.len = p - file;
    file = p + 1;
  }
  p = strrchr( file, '/' );
  if( p ) {
    f->f_dir.ptr = file;
    f->f_dir.len = p - file;
    if( !f->f_dir.len ) {
      f->f_dir.len = 1;
    }
    file = p + 1;
  }
  end = file + strlen( file );
  if( ( p = strchr( file, '(' ) ) && end[-1] == ')' ) {
    f->f_member.ptr = p + 1;
    f->f_member.len = end - p - 2;
    end = p;
  }
  p = 0;
  q = file;
  while( ( q = ( char * )memchr( q, '.', end - q ) ) ) {
    p = q++;
  }
  if( p ) {
    f->f_suffix.ptr = p;
    f->f_suffix.len = end - p;
    end = p;
  }
  f->f_base.ptr = file;
  f->f_base.len = end - file;
}

void path_build( PATHNAME *f, char *file, int binding ) {
  if( f->f_grist.len ) {
    if( f->f_grist.ptr[0] != '<' ) {
      *file++ = '<';
    }
    memcpy( file, f->f_grist.ptr, f->f_grist.len );
    file += f->f_grist.len;
    if( file[-1] != '>' ) {
      *file++ = '>';
    }
  }
  if( f->f_root.len
      && !( f->f_root.len == 1 && f->f_root.ptr[0] == '.' )
      && !( f->f_dir.len && f->f_dir.ptr[0] == '/' ) ) {
    memcpy( file, f->f_root.ptr, f->f_root.len );
    file += f->f_root.len;
    *file++ = PATH_DELIM;
  }
  if( f->f_dir.len ) {
    memcpy( file, f->f_dir.ptr, f->f_dir.len );
    file += f->f_dir.len;
  }
  if( f->f_dir.len && ( f->f_base.len || f->f_suffix.len ) ) {
    if( !( f->f_dir.len == 1 && f->f_dir.ptr[0] == PATH_DELIM ) ) {
      *file++ = PATH_DELIM;
    }
  }
  if( f->f_base.len ) {
    memcpy( file, f->f_base.ptr, f->f_base.len );
    file += f->f_base.len;
  }
  if( f->f_suffix.len ) {
    memcpy( file, f->f_suffix.ptr, f->f_suffix.len );
    file += f->f_suffix.len;
  }
  if( f->f_member.len ) {
    *file++ = '(';
    memcpy( file, f->f_member.ptr, f->f_member.len );
    file += f->f_member.len;
    *file++ = ')';
  }
  *file = 0;
}

void path_parent( PATHNAME *f ) {
  f->f_base.ptr =
    f->f_suffix.ptr =
      f->f_member.ptr = "";
  f->f_base.len =
    f->f_suffix.len =
      f->f_member.len = 0;
}
